import React, { useEffect, useState } from 'react'
import { observer, useLocalObservable } from 'mobx-react'
import Store from '../../store'
import styles from './index.module.less'
import { Input, Mask } from 'antd-mobile'
import successBtn from '@/resource/home/success.png'
import cancelBtn from '@/resource/home/cancel.png'
import { history } from 'umi'
import type { ModalPropsType } from '../../interface'
import { api } from '@/servers/api'
import { putData } from '@/servers/http'

const EditModal = observer((props: ModalPropsType<{ idx: number; levelId: string }>) => {
    const { idx, onClose, onOk, visible, levelId } = props
    const store = useLocalObservable(() => Store)
    const { questionList, updateAnswer, info } = store
    const [value, setValue] = useState(questionList?.[idx]?.answer)

    const textLimit = [20, 100, 100, 100, 50, 100, 100]

    useEffect(() => {
        if (visible) {
            setValue(questionList?.[idx]?.answer || '')
        }
    }, [idx, questionList, visible])

    /** 更新 */
    function handleUpdate() {
        return putData(`${api.userBarriersBatchUpdate}${levelId}`, {
            id: questionList?.[idx].editId,
            answer: value,
        }).then(res => {})
    }

    /** 提交 */
    const handleSubmit = () => {
        if (value) {
            if (info?.detail?.length > 0) {
                handleUpdate().then(() => {
                    updateAnswer(value, idx)
                })
            } else {
                updateAnswer(value, idx)
            }
            onOk()
        }
    }

    if (!visible) {
        return null
    }
    return (
        <div className={styles.modal_container} style={{ display: visible ? 'block' : 'none' }}>
            <Mask visible />
            <div className={styles.modal_content}>
                <div className={styles.title}>修改{questionList?.[idx]?.answer_title}</div>
                <div className={styles.input_wrapper}>
                    <Input className={styles.input} value={value} onChange={setValue} maxLength={textLimit[idx]} />
                </div>
                <div className={styles.footer}>
                    <img src={cancelBtn} onClick={onClose} />
                    <img src={successBtn} onClick={handleSubmit} />
                </div>
            </div>
        </div>
    )
})

export default EditModal
